import React, { useEffect, useState } from "react";
import './login.css';
import '../Loan/Apply/apply.css'
import NavigateBar from "@/components/NavigateBar";
import { useDispatch } from "react-redux";
import { DotLoading, Mask, Toast } from "antd-mobile";
import { useHistory } from "react-router-dom/cjs/react-router-dom";
import icon_app_logo from "@/assets/icon_app_logo.png"
import icon_login_refuse from "@/assets/icon_login_refuse.png"
import icon_login_account_creat from '@/assets/icon_login_account_creat.png'
import icon_login_account from '@/assets/icon_login_account.png'
import icon_facebook from '@/assets/icon_facebook.png'
import icon_login_phone from '@/assets/icon_login_phone.png'
import "../../App.css";
import { PageTag } from "@/utils/pageTag";
import { isLoanLoaning, isLoanReject, isLoanRepayNow, isLoanReviewing, isLoanSigning } from "@/utils/loanStatus";
import { removeUserInfo } from "@/utils/storage";
import { isArray } from "@/utils/utils";
import FacebookData from "@/utils/facebookData";
import AddHomeEvent from "@/utils/addHomeEvent";
import { reqFbUnionLogin, reqSaveEvent, reqUserState } from "@/store/actions/apiServices";
import { useLocation } from "react-router-dom/cjs/react-router-dom.min";


/**
 * 登录页
 */
export default function LoginFB() {

    //loading状态
    const [maskVisible, setMaskVisible] = useState(false)

    //显示add home弹框
    const [addHomeMaskVisible, setAddHomeMaskVisible] = useState(false);
    const [addHomeMaskIsHomeMode, setAddHomeMaskIsHomeMode] = useState(false);

    //需要转登录状态
    const [needToLoginPage, setNeedToLoginPage] = useState(false);

    //需要转注册状态
    const [needToRegisterPage, setNeedToRegisterPage] = useState(false);

    //不在服务地区弹框
    const [notInServiceLocation, setNotInServiceLocation] = useState(false);

    //不在年龄区弹框
    const [notInServiceAgeRange, setNotInServiceAgeRange] = useState(false);

    //fb登录状态
    const [fbLoginMsg, setFbLoginMsg] = useState(null);

    //fb用户状态
    const [fbUserMsg, setFbUserMsg] = useState(null)

    //fb好友状态
    const [fbFriendsMsg, setFbFriendsMsg] = useState(null);

    //fb用户状态
    const [fbLogoutMsg, setFbLogoutMsg] = useState(null)

    //fb用户id
    const [fbUserId, setFbUserId] = useState(null)

    //fb用户名
    const [fbUserName, setFbUserName] = useState(null)

    //router
    const history = useHistory()
    const location = useLocation()

    // 获取 Redux 分发器
    const dispatch = useDispatch()

    const onReqUserStateCallback = (success, resObj) => {
        setMaskVisible(false);
        if (success && resObj) {
            //是否为签约中
            const isHomeSigning = isLoanSigning(resObj.signFlag, resObj.signOrderId)
            //是否为审核中
            const isHomeReviewing = isLoanReviewing(resObj.applyStatus)
            //是否为拒绝
            const isHomeReject = isLoanReject(resObj.applyStatus, resObj.orderStatus)
            //是否为放款中
            const isHomeLoaning = isLoanLoaning(resObj.orderStatus)
            //是否为待还款
            const isHomeRepay = isLoanRepayNow(resObj.orderStatus)
            //是否为待进件
            const isHomeNotLoan = ((!isHomeReviewing) && (!isHomeReject) && (!isHomeLoaning) && (!isHomeRepay))
            console.log("Launch-isHomeReviewing: " + isHomeReviewing)
            console.log("Launch-isHomeReject: " + isHomeReject)
            console.log("Launch-isHomeLoaning: " + isHomeLoaning)
            console.log("Launch-isHomeRepay: " + isHomeRepay)
            console.log("Launch-isHomeNotLoan: " + isHomeNotLoan)
            console.log("Launch-isHomeSigning: " + isHomeSigning)

            if (isHomeSigning) {
                history.replace('/guide')
            } else if (isHomeReviewing) {
                history.replace('/review')
            } else if (isHomeReject) {
                history.replace('/reject')
            } else if (isHomeLoaning) {
                history.replace('/loaning')
            } else if (isHomeRepay) {
                history.replace('/repay')
            } else {
                history.replace('/home')
            }
        }
    };


    //清空登录信息
    useEffect(() => {
        console.log("LOGIN-移除登录信息")
        //移除登录信息
        removeUserInfo()

        //来源
        const dreferrer = document.referrer || ""
        console.log("document.referrer:==========" + dreferrer)

        //来源参数
        const queryParams = new URLSearchParams(location.search);
        const isRegister = queryParams.get('isRegister') || ""
        console.log("isRegister:" + isRegister);

        //fb登录状态查询
        checkFacebookLoginStatus()

        //打点
        reqSaveEvent("LOGIN_FB_UNION_START")

        return () => {
            //打点
            reqSaveEvent("LOGIN_FB_UNION_END")
        }
    }, [])

    //获取用户流程信息
    const getUserStateInfo = () => {
        try {
            setMaskVisible(true);
            reqUserState(PageTag.LOGIN, onReqUserStateCallback);
        } catch (e) {
            console.log(e)
        }
    }

    // 用fb联合登录
    const doFacebookUnionLogin = (pageType = "LOGINPAGE") => {
        try {
            if (FacebookData.facebookUserInfo) {
                reqSaveEvent("LOGIN_FB_" + pageType)
                let facebookUserId = FacebookData.facebookUserInfo.id || ""

                setMaskVisible(true);
                reqFbUnionLogin(facebookUserId, pageType, (success, resObj) => {
                    setMaskVisible(false);
                    if (success) {
                        //是否做了基本信息，做了的话，不需要拦截
                        const basicAuthState = resObj.basicAuthState
                        if (basicAuthState && basicAuthState === 'YES') {
                            //查询用户状态
                            getUserStateInfo()

                        } else {
                            //判断是否合法的地区下年龄段
                            const isNigeriaZone = true//FacebookData.isNigeriaZone()
                            const isValidAgeRange = true//FacebookData.isValidAgeRange()

                            if (!isNigeriaZone) {
                                setNotInServiceLocation(true)
                            }
                            if (!isValidAgeRange) {
                                setNotInServiceAgeRange(true)
                            }
                            if (isNigeriaZone && isValidAgeRange) {
                                //查询用户状态
                                getUserStateInfo()
                            }
                        }

                        //保存fb user info
                        FacebookData.saveUserInfo()

                        //抓取fb联系人信息
                        FacebookData.saveUserFriends()
                    } else {
                        //判断弹框
                        const otpResCode = resObj.resCode || -1
                        if (otpResCode === 2001) {
                            //需要弹提示--你是新客，需要注册
                            setNeedToRegisterPage(true)
                            setNeedToLoginPage(false)

                        } else if (otpResCode === 2002) {
                            //需要弹提示--你是旧客，需要登录
                            setNeedToRegisterPage(false)
                            setNeedToLoginPage(true)
                        }
                    }
                });

            } else {
                console.log("===========set fbUserInfo not success")
            }
        } catch (e) {
            console.log(e)
        }
    }

    // fb登录成功-获取数据
    const doFetchFbFriendsInfo = async (userID) => {

        let resMsg = "Friends Info:\n"

        // 使用访问令牌调用 Facebook Graph API 获取用户信息
        window.FB && window.FB.api("/me/friends", { fields: 'id,name' }, function (userResponse) {
            console.log(userResponse)

            if (userResponse && !userResponse.error) {
                resMsg = resMsg + "Fetch frinds success:\n"
                const list = userResponse.data;
                const isArrayList = isArray(list)
                resMsg = resMsg + "isArrayList: " + isArrayList + "\n"
                if (isArrayList) {
                    resMsg = resMsg + "list size: " + list.length + "\n"
                }
                list.forEach((item) => {
                    const userID = item.id;
                    const userName = item.name;
                    const userPicture = item.picture;
                    const userEmail = item.email;
                    const userLink = item.link;
                    const userLocation = item.location;
                    const userHometown = item.hometown;
                    const userBirthday = item.birthday;
                    const userAgeRange = item.age_range;
                    const userGender = item.gender;

                    resMsg = resMsg + "userID: " + userID + "\n"
                    resMsg = resMsg + "userName: " + userName + "\n"
                    resMsg = resMsg + "userPicture: " + userPicture + "\n"
                    resMsg = resMsg + "userEmail: " + userEmail + "\n"
                    resMsg = resMsg + "userLink: " + userLink + "\n"
                    resMsg = resMsg + "userLocation: " + userLocation + "\n"
                    resMsg = resMsg + "userHometown: " + userHometown + "\n"
                    resMsg = resMsg + "userBirthday: " + userBirthday + "\n"
                    resMsg = resMsg + "userAgeRange: " + userAgeRange + "\n"
                    resMsg = resMsg + "userGender: " + userGender + "\n"
                    resMsg = resMsg + "==============\n"
                });

            } else {
                resMsg = resMsg + "Fetch frinds err:\n"
                resMsg = resMsg + userResponse.error + "\n"

                // 处理错误
                console.log('Fetch frinds err:', userResponse.error);
            }

            //刷新
            setFbFriendsMsg(resMsg)
        });
    }

    // fb登录成功-获取数据
    const doFetchFbUserInfoWhenLoginSuccess = async (pageType = "LOGINPAGE") => {
        // 使用访问令牌调用 Facebook Graph API 获取用户信息
        window.FB && window.FB.api('/me', { fields: 'id,name,picture,email,link,location,hometown,birthday,age_range,gender' }, function (userResponse) {
            console.log(userResponse)

            if (userResponse && !userResponse.error) {
                //保存fb id
                const userID = userResponse.id || "";
                FacebookData.facebookUserId = userID
                FacebookData.facebookUserInfo = { ...userResponse }
                console.log("======= set facebookUserId: " + userID)

                //保存用户数据
                console.log("========= set fbUserInfo")
                console.log(FacebookData.facebookUserInfo)

                //系统登录
                doFacebookUnionLogin(pageType)

            } else {
                Toast.show(userResponse.error)
                // 处理错误
                console.log('Fetch user info err:', userResponse.error);

                //打点
                reqSaveEvent("FB_SDK_GET_USER_INFO_ERR", userResponse.error || "error")
            }
        });
    }

    // 登录-fb登录
    const doFacebookLogin = async (pageType = "LOGINPAGE") => {
        window.FB && window.FB.login(function (response) {
            console.log("============ FB Login: ")

            //打点
            reqSaveEvent("FB_SDK_LOGIN_STATUS", response.status || "unknown")

            if (response.status === 'connected') {
                // 用户已登录并授权你的应用程序
                //获取用户信息
                doFetchFbUserInfoWhenLoginSuccess(pageType)

            } else if (response.status === 'not_authorized') {
                // 用户已登录但未授权你的应用程序
                Toast.show("Facebook login not authorized")

            } else {
                // 用户未登录 Facebook，或者登录状态未知
                Toast.show("Facebook login fail")
            }

        }, { scope: 'public_profile,email,user_friends,user_link,user_location,user_hometown,user_birthday,user_age_range,user_gender' });
    }

    // 注册-fb登录
    const onHandleRegisterWithFacebookAccount = () => {
        //打点
        reqSaveEvent("LOGIN_CREATE_WITH_FACEBOOK_CLICK")

        //判断是否已经登录
        window.FB && window.FB.getLoginStatus(function (response) {
            if (response.status === 'connected') {
                // 用户已登录并授权你的应用，则退出
                window.FB && window.FB.logout(function (response) {
                    //这个时候再去登录
                    doFacebookLogin("REGPAGE")
                });
            } else {
                //这个时候再去登录
                doFacebookLogin("REGPAGE")
            }
        });
    }

    // 登录-退出fb登录
    const onHandleLogoutFacebookAccount = () => {
        let resMsg = "Logout: \n"

        // 注销用户
        window.FB && window.FB.logout(function (response) {
            if (response.status === 'unknown') {
                resMsg = resMsg + "success\n"

                // 用户已成功退出登录
                console.log('用户已退出登录');
            } else {
                resMsg = resMsg + "error\n"

                // 注销时发生错误
                console.log('注销时出错:', response);
            }

            //刷新
            setFbLogoutMsg(resMsg)
        });
    }

    // 登录-判断facebook登录状态
    const checkFacebookLoginStatus = () => {
        window.FB && window.FB.getLoginStatus(function (response) {
            if (response.status === 'connected') {
                // 用户已登录并授权你的应用
                var accessToken = response.authResponse.accessToken;
                console.log('用户已登录，访问令牌：' + accessToken);

                // 使用访问令牌调用 Facebook Graph API 获取用户信息
                window.FB && window.FB.api('/me', { fields: 'id,name' }, function (userResponse) {
                    console.log(userResponse)

                    if (userResponse && !userResponse.error) {
                        const userID = userResponse.id || null;
                        const userName = userResponse.name || null;

                        //更新button显示
                        setFbUserId(userID)
                        setFbUserName(userName)

                    } else {
                        //更新button显示
                        setFbUserId(null)
                        setFbUserName(null)
                    }
                });

            } else if (response.status === 'not_authorized') {
                // 用户已登录到Facebook，但未授权你的应用
                console.log('用户已登录到Facebook,但未授权你的应用');
                //更新button显示
                setFbUserId(null)
                setFbUserName(null)

            } else {
                // 用户未登录到Facebook
                console.log('用户未登录到Facebook');
                //更新button显示
                setFbUserId(null)
                setFbUserName(null)
            }
        });
    }

    // 登录-fb登录
    const onHandleLoginWithFacebookAccount = () => {
        //打点
        reqSaveEvent("LOGIN_WITH_FACEBOOK_CLICK")

        //判断是否已经登录
        window.FB && window.FB.getLoginStatus(function (response) {
            if (response.status === 'connected') {
                // 用户已登录并授权你的应用，则退出
                window.FB && window.FB.logout(function (response) {
                    //这个时候再去登录
                    doFacebookLogin("LOGINPAGE")
                });
            } else {
                //这个时候再去登录
                doFacebookLogin("LOGINPAGE")
            }
        });
    }


    // 登录-fb登录--已登录状态
    const onHandleLoginWithFacebookAccountWhenFacebookDidLogin = () => {
        //打点
        reqSaveEvent("LOGIN_WITH_FACEBOOK_CLICK")

        //这个时候再去登录
        doFacebookLogin("LOGINPAGE")
    }

    // 切换手机号登录
    const onHandlePhoneMobileLogin = () => {
        //打点
        reqSaveEvent("LOGIN_WITH_PHONE_NUMBER_CLICK")

        history.push({ pathname: '/login', search: '?isRegister=NO' })
    }

    // 切换手机号注册
    const onHandlePhoneMobileRegister = () => {
        //打点
        reqSaveEvent("LOGIN_WITH_PHONE_NUMBER_CLICK")

        history.push({ pathname: '/login', search: '?isRegister=YES' })
    }

    // 点击add home监听
    const onHandleAddToHome = (type) => {
        console.log(`点击add home监听: ${type}`)
        if (type === 'home') {
            AddHomeEvent.onHandleAddHomeEventClick()
        } else {
            AddHomeEvent.onHandleAddFavoriteEventClick()
        }
    }

    // 关闭add home
    const onHandleAddToHomeClose = () => {
        console.log(`点击close add home监听`)
        setAddHomeMaskVisible(false)
    }


    return (
        <div className="login">
            <NavigateBar theme="white" showLogout={false} onAddFavorite={() => { setAddHomeMaskIsHomeMode(false); setAddHomeMaskVisible(true) }} onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }}></NavigateBar>

            <div className="pageContentColumn contentHorizontalPadding loginTopEdge10Px">
                <div className='loginApp'>
                    <div className='loginAppLogoContent'>
                        <img className="loginAppLogo" src={icon_app_logo} alt='' />
                        <span className='loginAppName'>Onua Credit</span>
                    </div>
                    <span className='loginAppUser'>www.allproductghs.online</span>
                </div>

                <div className="columnAlignStartFullWidth">
                    <div className="rowAlignStart loginTitle">Safe and fast personal loan platform</div>

                    <div className="columnAlignStartFullWidth loginMenuBackground">
                        <div className="rowAlignStart">
                            <img className="loginMenuLogo" src={icon_login_account_creat} alt='' />
                            <span className='loginMenuTitle'>Create an account for new user</span>
                        </div>

                        <div className="rowAlignCenterFullWidth loginMenuBtnBackground">
                            <div className="rowAlignCenterFullWidth loginMenuBtn" onClick={onHandleRegisterWithFacebookAccount}>
                                <img className="loginMenuLogo" src={icon_facebook} alt='' />
                                <span>Continue with Facebook</span>
                            </div>
                        </div>
                    </div>

                    <div className="columnAlignStartFullWidth loginMenuBackground">
                        <div className="rowAlignStart">
                            <img className="loginMenuLogo" src={icon_login_account} alt='' />
                            <span className='loginMenuTitle'>Login my account</span>
                        </div>

                        <div className="rowAlignCenterFullWidth loginMenuBtnBackground">
                            {!fbUserName && <div className="rowAlignCenterFullWidth loginMenuBtn" onClick={onHandleLoginWithFacebookAccount}>
                                <img className="loginMenuLogo" src={icon_facebook} alt='' />
                                <span>Login with Facebook</span>
                            </div>}
                            {fbUserName && <div className="rowAlignCenterFullWidth loginMenuBtn" onClick={onHandleLoginWithFacebookAccountWhenFacebookDidLogin}>
                                <img className="loginMenuLogo" src={icon_facebook} alt='' />
                                <span>Continue as {(fbUserName.length > 7) ? (fbUserName.substring(0, 5) + "...") : fbUserName}</span>
                            </div>}
                        </div>

                        <div className="rowAlignCenterFullWidth loginMenuBtnBackground" onClick={onHandlePhoneMobileLogin}>
                            <div className="rowAlignCenterFullWidth loginMenuBtnForPhone">
                                <img className="loginMenuLogo" src={icon_login_phone} alt='' />
                                <span>Login with Phone number</span>
                            </div>
                        </div>
                    </div>
                </div>

                <Mask visible={needToLoginPage} opacity={0.1}
                    onMaskClick={() => { }}>
                    <div className="applyOverlayBg">
                        <div className="applyOverlayContent">
                            <div className="applyOverlayContentIconCenter" onClick={() => { setNeedToLoginPage(false) }}>
                                <img className="applyOverlayIconCenter" src={icon_login_refuse} alt="" />
                            </div>

                            <div className="applyOverlayContentRowTitle">It is detected that you have already registered an account.</div>
                            <div className="applyOverlayContentRowTitle">Please login to your account through the login portal.</div>

                            <div className="homeApplyBtnLarge loginTopEdge" onClick={() => { setNeedToLoginPage(false) }}>
                                <div className="mainButtonGradient">OK</div>
                            </div>
                        </div>
                    </div>
                </Mask>

                <Mask visible={needToRegisterPage} opacity={0.1}
                    onMaskClick={() => { }}>
                    <div className="applyOverlayBg">
                        <div className="applyOverlayContent">
                            <div className="applyOverlayContentIconCenter" onClick={() => { setNeedToRegisterPage(false) }}>
                                <img className="applyOverlayIconCenter" src={icon_login_refuse} alt="" />
                            </div>

                            <div className="applyOverlayContentRowTitle">No account has been registered with this identity information.</div>
                            <div className="applyOverlayContentRowTitle">Please change your identity to log in or register a new account.</div>

                            <div className="homeApplyBtnLarge loginTopEdge" onClick={() => { setNeedToRegisterPage(false) }}>
                                <div className="mainButtonGradient">OK</div>
                            </div>
                        </div>
                    </div>
                </Mask>

                {/* <AddToHomeGifDialog visible={addHomeMaskVisible} onConfirm={onHandleAddToHome} onClose={onHandleAddToHomeClose} isHomeMode={addHomeMaskIsHomeMode} /> */}

                <Mask visible={maskVisible} opacity={0.1}
                    onMaskClick={() => { }}>
                    <div className="overlayContent">
                        <span style={{ fontSize: 24, color: '#ff3141' }} >
                            <DotLoading color="currentColor" />
                        </span>
                    </div>
                </Mask>
            </div>
        </div >
    )
}